package org.example.servicecounselor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.model.student.bean.Task;
import org.example.servicecounselor.mapper.TaskMapper;
import org.example.servicecounselor.service.TaskService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-08-03
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public List<Task> getByMajorId(Integer majorId) {
        List<Task> list = redisTemplate.opsForList().range("task:" + majorId, 0, -1);
        if (list != null && !list.isEmpty()) {
            return list;
        }
        list = taskMapper.selectList(new QueryWrapper<Task>().eq("major_id", majorId));
        redisTemplate.opsForList().rightPushAll("task:" + majorId, list);
        return list;
    }

    @Override
    public int changeTask(Task task) {
        task.setUpdateTime(new Date());
        redisTemplate.delete("task:" + task.getMajorId());
        rabbitTemplate.convertAndSend("task.update.fanout", "", task);

        return taskMapper.update(task, new QueryWrapper<Task>().eq("major_id", task.getMajorId()).eq("task_id", task.getTaskId()));
    }

    @Override
    public int deleteTask(Integer majorId, Integer taskId) {
        int num = taskMapper.delete(new QueryWrapper<Task>().eq("major_id", majorId).eq("task_id", taskId));
        redisTemplate.delete("task:" + majorId);
        rabbitTemplate.convertAndSend("task.delete.fanout", "", new Integer[]{majorId, taskId});
        return num;
    }

    @Override
    public void sendTask(Task task) {
        Long id = taskMapper.selectCount(new QueryWrapper<Task>().eq("major_id", task.getMajorId()));
        task.setTaskId(id.intValue() + 1);
        taskMapper.insert(task);
        redisTemplate.opsForList().rightPush("task:" + task.getMajorId(), task);
        rabbitTemplate.convertAndSend("task.add.fanout", "", task);
    }
}